<template>
  <ContentCard>
    <template #header>
      <pageHeaderNew :title="title" :breadCrumb="breadCrumb" showBack>
      </pageHeaderNew>
    </template>
    <ConditionBox :margin-bottom="20">
      <template #left>
        <a-input-search
          @press-enter="search"
          @search="search"
          :style="{ width: '320px' }"
          placeholder="请输入模板名称"
          search-button
          v-model="keyWord"
        />
      </template>
      <template #right>
        <a-button @click="add" type="primary">新增模板</a-button>
      </template>
    </ConditionBox>
    <table-turn :table-data="tableData" ref="tableRef">
      <a-table-column align="center" :width="80">
        <template #title> 序号 </template>
        <template #cell="{ rowIndex }">
          {{ rowIndex + 1 }}
        </template>
      </a-table-column>
      <a-table-column
        :width="200"
        dataIndex="name"
        align="center"
        title="模板名称"
      ></a-table-column>
      <a-table-column
        :width="200"
        dataIndex="remark"
        align="center"
        title="模板描述"
      ></a-table-column>
      <!-- <a-table-column
      :width="200"
      align="center"
      dataIndex="userName"
      title="创建人"
    ></a-table-column>
    <a-table-column
      :width="200"
      align="center"
      dataIndex="positionSequenceName"
      title="创建时间"
    ></a-table-column> -->
      <a-table-column
        :width="200"
        align="center"
        dataIndex="enable"
        title="启用状态"
      >
        <template #cell="{ record }">
          {{ record.enable === 1 ? '启用' : '禁用' }}
        </template>
      </a-table-column>
      <a-table-column
        :width="200"
        align="center"
        dataIndex="positionSequenceName"
        title="设为默认"
      >
        <template #cell="{ record }">
          <a-switch
            @change="changeRequired(record)"
            v-model="record.required"
            :checked-value="1"
            :unchecked-value="2"
          />
        </template>
      </a-table-column>
      <a-table-column title="操作" align="center" :width="120" fixed="right">
        <template #cell="{ record }">
          <a-space :size="0">
            <a-tooltip content="预览">
              <icon-eye
                size="20"
                @click="look(record, 'see')"
                style="
                  padding-bottom: 3px;
                  padding-right: 10px;
                  color: #5085ff;
                  cursor: pointer;
                "
              />
            </a-tooltip>
            <a-tooltip content="复制">
              <a-popconfirm content="是否确认复制该条数据?" @ok="copy(record)">
                <icon-copy
                  size="18"
                  style="
                    padding-bottom: 3px;
                    padding-right: 10px;
                    color: #5085ff;
                    cursor: pointer;
                  "
                />
              </a-popconfirm>
            </a-tooltip>
            <a-tooltip content="编辑">
              <icon-font
                type="icon-edit"
                :size="26"
                @click="goEdit(record)"
                :style="{
                  cursor: 'pointer'
                }"
              />
            </a-tooltip>
            <a-tooltip content="删除" position="left">
              <a-popconfirm content="是否确认删除该条数据?" @ok="del(record)">
                <icon-font
                  type="icon-delete"
                  :size="26"
                  :style="{
                    cursor: 'pointer'
                  }"
                />
              </a-popconfirm>
            </a-tooltip>
          </a-space>
        </template>
      </a-table-column>
    </table-turn>
  </ContentCard>
  <NoticeTemplate
    ref="templateRef"
    :data="currRecord.data"
    :business-type="businessType"
    :add="addData"
    :tab-code-list="businessType"
    :edit="EditData"
    :fn="tableRef"
    title="入职方案模板"
  ></NoticeTemplate>
  <a-modal
    v-model:visible="visible"
    width="50%"
    :hide-cancel="true"
    ok-text="关闭"
  >
    <template #title> {{ lookData.data.name }} </template>
    <div style="display: flex; margin-right: 30px">
      <a-anchor :change-hash="false">
        <a-anchor-link
          v-for="item in lookData.data.details"
          :href="`#${item.code}`"
          :key="item.code"
          >{{ item.name }}</a-anchor-link
        >
      </a-anchor>
      <div style="height: 600px; flex: 1">
        <div
          class="subDetail"
          v-for="item in lookData.data.details"
          :key="(item.subCode as string)"
          :id="item.code"
        >
          <div class="head">
            <div class="sub-title">
              <p class="icon"></p>
              {{ item.name }}
            </div>
          </div>
          <div style="width: 90%; margin: auto">
            <a-form ref="HumanForm" :model="item.componentModel" autoLabelWidth>
              <a-row :gutter="16">
                <a-col
                  v-for="(ele, index) in item?.componentModel"
                  :key="index"
                  :span="(ele?.span as number)"
                >
                  <FormItem
                    :disabled="true"
                    :componentType="(ele?.ctlComponentType as string)"
                    :props="(ele?.props as any)"
                    :name="(ele?.ctlCnName as string)"
                    :required="(ele?.required as any)"
                    v-model:values="ele.controlValue"
                    :code="(ele?.ctlCode as any)"
                  />
                </a-col>
              </a-row>
            </a-form>
          </div>
        </div>
      </div>
    </div>
  </a-modal>
</template>

<script setup lang="ts">
import {
  GetEntryScheme,
  DelEntryScheme,
  AddEntryScheme,
  EditEntryScheme,
  GetEntrySchemeById,
  EditEntrySchemeDefault
} from '@/apis/management/personnel/baseSetting/TransactionSetting';
import FormItem from '@/components/DynamicFormsNew/RenderingForm/FormItem/index.vue';
import clonedeep from 'lodash.clonedeep';
import { Message } from '@arco-design/web-vue';
const title = '入职方案模板列表';
const breadCrumb: string[] = ['人事', '基础设置', '入职方案模板设置'];
const keyWord = ref('');
const visible = ref(false);
let templateRef = ref();
const businessType = ref([
  'SER_FUNC999495CA19CE4E7EA196944A911B3B41',
  'baseComponent'
]);
// 搜索
const search = () => {
  tableRef.value.loadData();
};
// 删除
const del = async (data: any) => {
  try {
    if (data.required === 1) {
      return Message.error('默认模板无法删除');
    }
    await DelEntryScheme({ id: data.id });
    tableRef.value.loadData();
  } catch (error) {
    console.log(error);
  }
};
const requiredId = ref<number>();
const tableRef = ref();
const tableData = async (page: any) => {
  try {
    const res: any = await GetEntryScheme({
      ...page,
      name: keyWord.value
    });
    res.content.forEach((ele: any) => {
      if (ele.required === 1) {
        requiredId.value = ele.id;
      }
    });
    return Promise.resolve(res);
  } catch (err: unknown) {
    console.log(err);
  }
};

const lookData: any = reactive({ data: {} });

// 储存当前数据
const currRecord: any = reactive({ data: {} });

// 点击新增模板按钮
const add = () => {
  templateRef.value.fullScreen();
};
// 编辑 初始化控件数据
const goEdit = async (record: any) => {
  record.seconds = await GetEntrySchemeById({ id: record.id });
  record.seconds.forEach((ele: any) => {
    ele.componentList = ele.componentModel;
    delete ele.componentModel;
    ele.componentList.forEach((item: any) => {
      const { ctlCnName, ctlEnName, ctlComponentType, ctlCode, ctlFieldName } =
        item;
      item.uuid = ctlCode;
      item.componentName = ctlCnName;
      item.componentType = ctlComponentType;
      item.code = ctlCode;
      item.fieldName = ctlFieldName;
      item.enName = ctlEnName;
    });
  });
  currRecord.data = record;
  templateRef.value.fullScreen();
};
// 新增 模板新增函数
const addData = async (data: any, componentList: any) => {
  const template = data;
  const hid = await AddEntryScheme({ level: 'Template', template });
  for (let ele of componentList) {
    for (let item of ele.componentList) {
      const collectionId = await AddEntryScheme({
        level: 'Collection',
        collection: { hid, code: item.code, name: item.name }
      });
      for (let items of item.componentList) {
        items.collectionId = collectionId;
      }
      await AddEntryScheme({
        level: 'Control',
        controls: [...item.componentList]
      });
    }
  }
  tableRef.value.loadData();
};
// 新增 模板编辑函数
const EditData = async (data: any, componentList: any) => {
  const template = data;
  const datas = clonedeep(componentList);
  await EditEntryScheme({ level: 'Template', template });
  for (let ele of datas) {
    await EditEntryScheme({
      level: 'Collection',
      collection: { id: ele.id, hid: ele.hid, code: ele.code, name: ele.name }
    });
    await EditEntryScheme({
      level: 'Control',
      controls: [...ele.componentList]
    });
  }
  currRecord.data = {};
  // const list = clonedeep(data);
  // list.seconds = [];
  // const component = clonedeep(componentList);
  // component.forEach((item: any) => {
  //   item.componentModel = item.componentList;
  //   delete item.componentList;
  //   list.seconds.push(item);
  // });
  // await EditEntryScheme(list);
  tableRef.value.loadData();
};

// 修改默认
const changeRequired = async (data: any) => {
  await EditEntrySchemeDefault({
    id: data.id
  });

  tableRef.value.loadData();
};
const look = async (oldData: any, type: string) => {
  lookData.data.name = oldData.name;
  lookData.data.details = await GetEntrySchemeById({ id: oldData.id });
  visible.value = true;
};
const copy = async (record: any) => {
  const res: any = await GetEntrySchemeById({ id: record.id });
  const templateData = { level: 'Template', template: clonedeep(record) };
  delete templateData.template.id;
  templateData.template.name += '-copy';
  templateData.template.required = 2;
  const hid = await AddEntryScheme(templateData);
  res.forEach((ele: any) => {
    delete ele.id;
    delete ele.hid;
    ele.componentModel.forEach((item: any) => {
      delete item.id;
      delete item.collectionId;
    });
  });
  for (const item of res) {
    const { code, name, componentModel } = item;
    const collectionId = await AddEntryScheme({
      level: 'Collection',
      collection: { hid, code, name }
    });
    for (let items of item.componentModel) {
      items.collectionId = collectionId;
    }
    await AddEntryScheme({
      level: 'Control',
      controls: [...componentModel]
    });
  }
  tableRef.value.loadData();
};
</script>
<style lang="less" scoped>
.arco-space {
  display: flex;
  justify-content: space-between;
  padding: 20px;
}
:deep(.arco-modal-body) {
  height: 600px !important;
}
.subDetail {
  // width: 70%;
  // height: 60vh;
  margin: auto;
  .head {
    box-sizing: border-box;
    border-radius: 4px;
    width: 100%;
    display: flex;
    justify-content: space-between;
    align-items: center;
    box-sizing: border-box;
    padding: 10px;
    background-color: #e8f0ff;
    margin: 20px 0;
    .sub-title {
      display: flex;
      align-items: center;
      .icon {
        border-radius: 4px;
        width: 6px;
        height: 70%;
        background-color: #3d7eff;
        height: 20px;
        padding: 0;
        margin: 3px 0;
        margin-right: 10px;
      }
    }
    .setting {
      color: #3d7eff;
      cursor: pointer;
    }
  }
}
</style>
